package com.exchange.web.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exchange.web.goods.entity.Goods;
import com.exchange.web.goods.entity.MyGoodsParm;
import com.exchange.web.goods.entity.dto.WxIndexParm;
import com.exchange.web.goods.entity.vo.goodsVO;
import com.exchange.web.goods.mapper.GoodsMapper;
import com.exchange.web.goods.service.GoodsService;
import com.exchange.web.home.entity.vo.ChartVO;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    static List<String> week_day = java.util.Arrays.asList("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日");
    static List<String> month = java.util.Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月");

    @Override
    public IPage<Goods> getMyOrder(MyGoodsParm parm) {
        //构造分页对象
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        return this.baseMapper.getMyOrder(page, parm.getUserId());
    }

    @Override
    public IPage<Goods> getSellOrder(MyGoodsParm parm) {
        //构造分页对象
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        return this.baseMapper.getSellOrder(page, parm.getUserId());
    }

    @Override
    public List<goodsVO> getGoodsList(WxIndexParm parm) {
        IPage<goodsVO> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        return this.baseMapper.getGoodsList(page, parm);
    }

    @Override
    public List<goodsVO> getGoodsIndexList(WxIndexParm parm) {
        IPage<goodsVO> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        return this.baseMapper.getGoodsIndexList(page, parm);
    }

    @Override
    public List<goodsVO> getGoodBuysList(WxIndexParm parm) {
        IPage<goodsVO> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());
        return this.baseMapper.getGoodBuysList(page, parm);
    }

    @Override
    public Integer getGoodBuysListTotal(WxIndexParm parm) {

        return this.baseMapper.getGoodBuysListTotal(parm);
    }

    @Override
    public Integer getGoodListTotal(WxIndexParm parm) {
        return this.baseMapper.getGoodListTotal(parm);
    }

    @Override
    public Integer getIndexGoodListTotal(WxIndexParm parm) {

        return this.baseMapper.getIndexGoodListTotal(parm);
    }

    @Override
    public void deleteGoodsReport(Long goodsId) {
        this.baseMapper.deleteGoodsReport(goodsId);
    }

    @Override
    public List<ChartVO> getChartsByWeek() {
        String[] datesList = getCurrentWeekTimestampRange();  // 获取当前周的日期数组
        List<ChartVO> chartVOS = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());  // 获取今天的日期字符串

        for (int i = 0; i < 7; i++) {
            ChartVO chartVO = new ChartVO();

            // 检查是否超过今天的日期
            if (datesList[i].compareTo(today) <= 0) {
                // 获取用户数
                int userNum = this.baseMapper.getChartsForUserNumByWeek(datesList[i]);

                // 获取商品闲置数
                int goodsNum = this.baseMapper.getChartsForGoodsNumByWeek(datesList[i]);

                // 获取商品求购数
                int goodsBuyNum = this.baseMapper.getChartsForGoodsBuyNumByWeek(datesList[i]);

                chartVO.setUser_num(userNum);
                chartVO.setGoods_sell_num(goodsNum);
                chartVO.setGoods_buy_num(goodsBuyNum);
            } else {
                // 今天之后的日期，设置为0
                chartVO.setUser_num(0);
                chartVO.setGoods_sell_num(0);
                chartVO.setGoods_buy_num(0);
            }

            chartVO.setWeek_day(week_day.get(i));
            chartVOS.add(chartVO);
        }

        return chartVOS;
    }

    @Override
    public List<ChartVO> getChartsByYear() {

        List<String[]> monthRanges = getMonthDateRanges();  // 默认获取当前年份的日期范围
        System.out.println(Arrays.toString(monthRanges.get(0)));
        List<ChartVO> chartVOS = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());  // 获取今天的日期字符串

        for (String[] range : monthRanges) {
//            System.out.println(range[0] + " - " + range[1] + " - " + today);
            ChartVO chartVO = new ChartVO();
            if (range[0].compareTo(today) <= 0) {
                Map<String, Object> params = new HashMap<>();
                params.put("startDate", range[0]);
                params.put("endDate", range[1]);

                // 获取用户数
                int userNum = this.baseMapper.getChartsForUserNumByYear(range[1]);
                // 获取商品闲置数
                int goodsNum = this.baseMapper.getChartsForGoodsNumByYear(range[1]);
                // 获取商品求购数
                int goodsBuyNum = this.baseMapper.getChartsForGoodsBuyNumByYear(range[1]);
                chartVO.setMonth(month.get(monthRanges.indexOf(range)));
                chartVO.setUser_num(userNum);
                chartVO.setGoods_sell_num(goodsNum);
                chartVO.setGoods_buy_num(goodsBuyNum);
            } else {
                chartVO.setUser_num(0);
                chartVO.setGoods_sell_num(0);
                chartVO.setGoods_buy_num(0);
                chartVO.setMonth(month.get(monthRanges.indexOf(range)));
            }

            chartVOS.add(chartVO);

        }

        return chartVOS;
    }


    public List<String[]> getMonthDateRanges() {
        List<String[]> monthRanges = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int currentYear = calendar.get(Calendar.YEAR);  // 获取当前年份

        for (int month = 0; month < 12; month++) {
            calendar.set(Calendar.YEAR, currentYear);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, 1);

            String startDate = sdf.format(calendar.getTime());  // 当月第一天

            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            String endDate = sdf.format(calendar.getTime());  // 当月最后一天

            monthRanges.add(new String[]{startDate, endDate});
        }
//        for (Object o : monthRanges) {
//
//            System.out.println(o.toString());
//        }

        return monthRanges;
    }


    public static String[] getCurrentWeekTimestampRange() {
        String[] datesForMySQL = new String[7];
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 设置到本周的第一天（周一）
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        // 遍历一周的每一天，设置每天的结束时间
        for (int i = 0; i < 7; i++) {
            setToEndOfDay(calendar);
            datesForMySQL[i] = sdf.format(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        return datesForMySQL;
    }

    /**
     * 将日历时间设置为午夜 00:00:00.000，即当天的开始。
     *
     * @param calendar Calendar 实例
     */
    private static void resetToMidnight(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    /**
     * 将日历时间设置为一天的结束 23:59:59.999。
     *
     * @param calendar Calendar 实例
     */
    private static void setToEndOfDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
    }

}
